<template>
    <Designer ref="designer" :template="template" @onDesigned="onDesigned" />
    <templateAddForm ref="templateAddFormRef" @ok="ok"/>
  </template>
  
  <script setup lang="ts">
  import { onMounted, ref } from "vue";
  import { getTemplate} from '@/api/goods/express';
  import { Designer } from "@sv-print/vue3";
  import "sv-print/dist/style.css"; // 一般在入口文件(index/main)添加
  import templateAddForm from './modules/addForm.vue';
  let template = ref({});
  const printTemplate = ref();
  let templateAddFormRef:any = ref();
  const templateInfo:any = ref({});
  const hiprint = ref({});
  const router = useRouter();
  const { proxy } = getCurrentInstance()
  const onDesigned = (e) => {
    printTemplate.value =  e.detail.printTemplate
    hiprint.value = e.detail.hiprint
  };
  const submit = () => {
    proxy.$nextTick(() => {
      if (router.currentRoute.value.query.id) {
        templateInfo.value.templateContent = JSON.stringify(printTemplate.value.getJson())
        console.log('templateInfo :>> ', templateInfo.value);
        proxy.$refs.templateAddFormRef.design(templateInfo.value)
      }else{
        proxy.$refs.templateAddFormRef.add({templateContent: JSON.stringify(printTemplate.value.getJson())})
      }
    })
  }
  const ok = () => {
    // router.push({ path: '/express/templateList' })
  }
  // 获取模板数据
  const getTemplateJson = async () => {
    const { data } = await getTemplate(router.currentRoute.value.query.id)
    templateInfo.value = data
    template.value = JSON.parse(data.templateContent)
    updateJson()
  }
  // 更新模板数据
  const updateJson = ()=> {
      if (printTemplate) {
        try {
          printTemplate.value.update(template.value)
        } catch (e) {
          proxy?.$modal.msgError(`更新失败: ${e}`)
        }
      }
    }
  onMounted(() => {
    // 添加保存按钮
    let savBtn = document.getElementsByClassName('svp-header-menu svelte-ien9fs sav-btn')[0]
    if (!savBtn) {
      let dom = document.getElementsByClassName('flex svp-flex-row basis-1/5 justify-end svelte-ien9fs')[0]
      const div = document.createElement('div')
      div.innerHTML = `<div class="svp-header-menu svelte-ien9fs sav-btn"><i class="svicon sv-save svelte-ien9fs"></i> 
            <p class="svelte-ien9fs">保存到系统</p></div>`
      div.onclick = submit
      dom.appendChild(div)
    }
    if (router.currentRoute.value.query.id) {
      getTemplateJson()
    }
  })
  </script>
  <style type="text/css" scoped>
    .sav-btn{
      cursor: pointer;position: fixed;
      bottom: 50px;
      right: 50px;
      color: #fff;
      background-color: #409eff;
      border-radius: 8px;
      padding: 10px 20px;
    }
  </style>
  <style type="text/css" >
    .SVPrint,.svp-designer{
        min-height: calc(100vh - 100px);
    }
    .hiprint-printPaper > div:not(.hiprint-printPaper-content){
      display: none;
    }
    .hiprint-paperNumber{
      display: none !important;;
      font-size: 0!important;
      color: #fff!important;
    }
  </style>